import { ref } from 'vue';

export function useCodeGeneration() {
  const generatedCode = ref('');

  const generateCode = (program, type_master, type_detail) => {
    // 确保 type_master 和 type_detail 是数组
    const masterFields = Array.isArray(type_master) ? type_master : [];
    const detailFields = Array.isArray(type_detail) ? type_detail : [];

    // 生成代码部分
    const genDetail = detailFields.map(field => `\t${field.name} LIKE ${program.detail_table}.${field.name}`).join(',\n');
    const genMaster = masterFields.map(field => `\t${field.name} LIKE ${program.master_table}.${field.name}`).join(',\n');
    const genListDetail = detailFields.map(field => `\tLET ${program.g_detail}.${field.name} = aws_ttsrv_getRecordField(l_node2, "${field.name}")`).join('\n');
    const genListMaster = masterFields.map(field => `\tLET ${program.g_master}.${field.name} = aws_ttsrv_getRecordField(l_node, "${field.name}")`).join('\n');

    const chkMasterValue = masterFields
      .filter(field => field.isNull === 'Y')
      .map(field => `
        IF cl_null( ${program.g_master}.${field.name} ) THEN
            LET g_status.code = -1 
            LET g_status.description=g_status.description,";缺少字段 ${field.name} 请维护数据"
            LET r_success = FALSE
            EXIT WHILE        
        END IF
    `).join('\n');

    const chkDetailValue = detailFields
      .filter(field => field.isNull === 'Y')
      .map(field => `
        IF cl_null( ${program.g_detail}.${field.name} ) THEN
            LET g_status.code = -1 
            LET g_status.description=g_status.description,";缺少字段 ${field.name} 请维护数据"
            LET r_success = FALSE
            EXIT WHILE        
        END IF
    `).join('\n');

    const defaultMaster = masterFields
      .filter(field => field.default)
      .map(field => `\tIF cl_null(${program.g_master}.${field.name})  THEN LET ${program.g_master}.${field.name} = "${field.default}" END IF`)
      .join('\n');

    const defaultDetail = detailFields
      .filter(field => field.default)
      .map(field => `\tIF cl_null(${program.g_detail}.${field.name})  THEN LET ${program.g_detail}.${field.name} = "${field.default}" END IF`)
      .join('\n');

    const genRequestMasterXml = masterFields.map(field => `\t\t\t\t\t<Field name="${field.name}" value=""/>`).join('\n');
    const genRequestDetailXml = detailFields.map(field => `\t\t\t\t\t<Field name="${field.name}" value=""/>`).join('\n');

    const requestXML = `{
        <Request>
            <Access>
                <Authentication user="tiptop" password="tiptop"/>
                <Connection application="ERP"/>
                <Organization name="NNJLH"/>
                <Locale language="zh_cn"/>
            </Access>
            <RequestContent>
                <Parameter>
                <Record></Record>
                </Parameter>
                <Document>
                <RecordSet id="1">
                    <Master name="${program.master_table}">
                    <Record>
                        ${genRequestMasterXml}
                    </Record>
                    </Master>
                    <Detail name="${program.detail_table}">
                    <Record>
                        ${genRequestDetailXml}
                    </Record>
                    </Detail>
                </RecordSet>
                </Document>
            </RequestContent>
        </Request>
}`;

    const responseXML = `{
        <Response>
            <Execution>
                <Status code="0" sglcode="0" description="单据生成成功"/>
            </Execution>
            <ResponseContent>
                <Parameter>
                    <Record>
                        <Field name="doc_no" value="单号"/>
                    </Record>
                </Parameter>
                <Document/>
            </ResponseContent>
        </Response>
    }`;

    // 生成代码...
    generatedCode.value = `
# 程序名称: ${program.name}
# 撰写人员: ${program.author}
# 撰写时间: ${new Date().toLocaleString()}

DATABASE ds

GLOBALS "../../../tiptop/config/top.global"
GLOBALS "../../../tiptop/aws/4gl/aws_ttsrv2_global.4gl" 

#数据返回
DEFINE g_resp	RECORD 
       docno	STRING
	END RECORD

#单号
DEFINE g_docno LIKE type_file.chr100
DEFINE p_inTransaction   LIKE type_file.num5

#单身数据
type  type_detail RECORD
${genDetail}
END RECORD

#单头数组
type  type_master RECORD
${genMaster},
${program.detail_table}  DYNAMIC ARRAY OF type_detail
END RECORD

#全局定义
DEFINE  ${program.g_master}	 RECORD  LIKE ${program.master_table}.*
DEFINE  ${program.g_detail}	 RECORD  LIKE ${program.detail_table}.*

################################################################################
# Descriptions...: 接口入口
# Memo...........:
# Usage..........: CALL ${program.name}()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${program.author}
# Modify.........:
################################################################################
FUNCTION ${program.name}()
 
 WHENEVER ERROR CONTINUE

    CALL aws_ttsrv_preprocess()    
    
    IF g_status.code = "0" THEN
       CALL ${program.name}_process()
    END IF

    CALL aws_ttsrv_postprocess()
 
END FUNCTION

################################################################################
# Descriptions...: 执行主干程序
# Memo...........:
# Usage..........: CALL ${program.name}_process()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${program.author}
# Modify.........:
################################################################################
FUNCTION ${program.name}_process() 

DEFINE l_param          RECORD      
       ${program.master_table}  DYNAMIC ARRAY OF type_master
END RECORD
DEFINE l_i,l_j,l_n,l_t             LIKE type_file.num10 
DEFINE l_cnt,l_cnt1,l_cnt2,l_cnt3,l_cnt5,l_cnt6     LIKE type_file.num10
DEFINE l_node,l_node1,l_node2          om.DomNode
DEFINE l_docno         LIKE type_file.chr100
DEFINE l_type          LIKE type_file.chr100
DEFINE l_code          LIKE type_file.chr100
DEFINE l_date          LIKE type_file.dat
DEFINE l_chr           LIKE type_file.chr50
DEFINE li_result       LIKE type_file.num5
DEFINE l_sql           STRING                                        
DEFINE l_success       LIKE type_file.num5

    LET g_success = 'Y'
    INITIALIZE g_resp.* TO NULL
    
    #判断是否有数据
    LET l_cnt = aws_ttsrv_getMasterRecordLength("${program.master_table}")            
    IF l_cnt = 0 THEN
      LET g_status.code = "-1"
      LET g_status.description = "No recordset processed!"
      RETURN
    END IF

    #-------资料开始获取 --------#
    BEGIN WORK	

    FOR l_i = 1 TO l_cnt	
        INITIALIZE ${program.g_master}.* TO NULL
        LET l_node = aws_ttsrv_getMasterRecord(l_i, "${program.master_table}")

        #------- 解析单头字段 --------#
        ${genListMaster}
        #------- 解析单头字段 --------#
			
        #------- 单头资料检核 --------#			
        CALL ${program.name}_chk_master() RETURNING l_success
        IF NOT l_success THEN
            LET g_status.code = -1
            LET g_status.description=g_status.description,";  数据集检查失败" 
            LET g_success = 'N'
            EXIT FOR 
        END IF 
        #------- 单头资料检核 --------#	
    
        #------- 单头资料写入 --------#
        CALL ${program.name}_ins_master() RETURNING l_success   
        IF NOT l_success THEN
            LET g_status.code = -1
            LET g_status.description=g_status.description,";  数据新增失败" 
            LET g_success = 'N'
            EXIT FOR 
        END IF
        #------- 单头资料写入 --------#

        FOR l_j = 1 TO l_cnt2
            INITIALIZE ${program.g_detail}.* TO NULL
            LET l_node2 = aws_ttsrv_getDetailRecord(l_node, l_j, "${program.detail_table}")
            
            #------- 单身资料获取 --------#
            ${genListDetail}
            #------- 单身资料获取 --------#
            
            #------- 单身资料检核 --------#
            CALL ${program.name}_chk_detail() RETURNING l_success
            IF NOT l_success THEN
                LET g_status.code = -1
                LET g_status.description=g_status.description,";  数据集检查失败" 
                LET g_success = 'N'
                EXIT FOR
            END IF
            #------- 单身资料检核 --------#

            #------- 单身资料写入 --------#	
            CALL ${program.name}_ins_detail() RETURNING l_success            
            IF NOT l_success THEN
                LET g_status.code = -1
                LET g_status.description=g_status.description,";  数据写入失败！"
                LET g_success = 'N'
                EXIT FOR
            END IF
            #------- 单身资料写入 --------#
        
        END FOR
    END FOR

    #------- 单号返回 --------#
    IF cl_null(g_resp.docno) THEN
        LET g_resp.docno = g_docno
    ELSE
        LET g_resp.docno = g_resp.docno,"|",g_docno
    END IF
    #------- 单号返回 --------#	
    
    #------- 事务判定 --------#
    IF g_success= 'Y' THEN
        COMMIT WORK
        LET g_status.code = 0
        LET g_status.description = "资料产生成功"
        CALL aws_ttsrv_addParameterRecord(base.TypeInfo.create(g_resp))
    ELSE
        ROLLBACK WORK
    END IF
    #------- 事务判定 --------#  
    
END  FUNCTION

################################################################################
# Descriptions...: 单头字段检查
# Memo...........:
# Usage..........: CALL ${program.name}_chk_master()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${program.author}
# Modify.........:
################################################################################
FUNCTION ${program.name}_chk_master()
DEFINE r_success   LIKE type_file.num5
DEFINE l_cnt       LIKE type_file.num5  

    LET r_success = TRUE

    WHILE TRUE

    #------- 非空判定 --------#      
    ${chkMasterValue}
    #------- 非空判定 --------#  

    #------- 默认值取值 --------#  
    ${defaultMaster}
    #------- 默认值取值 --------#

        EXIT WHILE 
    END WHILE

    RETURN r_success

END FUNCTION


################################################################################
# Descriptions...: 单身字段检查
# Memo...........:
# Usage..........: CALL ${program.name}_chk_detail()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${program.author}
# Modify.........:
################################################################################
FUNCTION ${program.name}_chk_detail()
DEFINE r_success   LIKE type_file.num5
DEFINE l_cnt       LIKE type_file.num5  

    LET r_success = TRUE

    WHILE TRUE

    #------- 非空判定 --------#      
    ${chkDetailValue}
    #------- 非空判定 --------#  

    #------- 默认值取值 --------#  
    ${defaultDetail}
    #------- 默认值取值 --------#

        EXIT WHILE 
    END WHILE

    RETURN r_success

END FUNCTION

################################################################################
# Descriptions...: 单头字段写入
# Memo...........:
# Usage..........: CALL ${program.name}_ins_master()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${program.author}
# Modify.........:
################################################################################
FUNCTION ${program.name}_ins_master()
DEFINE r_success   LIKE type_file.num5
DEFINE l_cnt       LIKE type_file.num5  

    LET r_success = TRUE

    IF NOT p_inTransaction THEN   
      BEGIN WORK
    END IF

    INSERT INTO ${program.master_table} VALUES ( ${program.g_master}.* )
    IF STATUS THEN
       LET g_status.code = -1
       LET g_status.description=g_status.description,";写入 ${program.master_table} 失败"
       LET r_success = FALSE 
       ROLLBACK WORK   
    END IF 

    RETURN r_success    

END FUNCTION

################################################################################
# Descriptions...: 单身字段写入
# Memo...........:
# Usage..........: CALL ${program.name}_ins_detail()
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${program.author}
# Modify.........:
################################################################################
FUNCTION ${program.name}_ins_detail()
DEFINE r_success   LIKE type_file.num5
DEFINE l_cnt       LIKE type_file.num5  

    LET r_success = TRUE

    IF NOT p_inTransaction THEN   
      BEGIN WORK
    END IF

    INSERT INTO ${program.detail_table} VALUES (${program.g_detail}.*)
    IF STATUS THEN
       LET g_status.code = -1
       LET g_status.description=g_status.description,";写入 ${program.detail_table} 失败"
       LET r_success = FALSE 
       ROLLBACK WORK   
    END IF 

    RETURN r_success    

END FUNCTION

################################################################################
# Descriptions...: 请求和返回的报文格式
# Memo...........:
# Usage..........: None
# Input parameter:  
# Return code....: 
# Date & Author..: ${new Date().toLocaleString()} By ${program.author}
# Modify.........:
################################################################################

${requestXML}

${responseXML}

`;

    return generatedCode.value;
  };


  return {
    generateCode,
    generatedCode
  };
}